import type { StatsCard } from "../../invitation-code/components/StatsCards.vue"
import { ref } from "vue"

// 渠道绩效数据接口
export interface ChannelPerformance {
  channel: string
  totalProducts: number
  completedCount: number
  completionRate: number
  userCount: number
  validAccountCount: number
  totalContent: number
  activeUsers: number
}

// 代理商排行数据接口
export interface TopAgent {
  rank: number
  name: string
  userCount: number
  contentCount: number
  badge?: string
}

// 图表数据接口
export interface ChartData {
  contentTrend: {
    dates: string[]
    published: number[]
    generated: number[]
  }
  versionActivity: {
    versions: string[]
    values: number[]
  }
}

// 用户版本分布接口
export interface UserVersionDistribution {
  name: string
  value: number
  color: string
}

// 选项接口
export interface SelectOption {
  label: string
  value: string | number
}

export function useDataReport() {
  // 页面状态
  const loading = ref(false)
  const timeRange = ref<string>("30")
  const channelFilter = ref<string>("all")

  // 时间范围选项
  const timeRangeOptions: SelectOption[] = [
    { label: "近7天", value: "7" },
    { label: "近30天", value: "30" },
    { label: "近90天", value: "90" }
  ]

  // 渠道选项
  const channelOptions: SelectOption[] = [
    { label: "全部渠道", value: "all" },
    { label: "华东区域", value: "east" },
    { label: "华南区域", value: "south" },
    { label: "华北区域", value: "north" }
  ]

  // 统计卡片数据
  const statsCards = ref<StatsCard[]>([
    {
      label: "总渠道数量",
      value: "470",
      description: "较昨日 +8%",
      icon: "TrendCharts",
      iconColor: "blue"
    },
    {
      label: "总代理用户",
      value: "319",
      description: "较昨日 68%",
      icon: "User",
      iconColor: "green"
    },
    {
      label: "总发布内容",
      value: "7420",
      description: "",
      icon: "Document",
      iconColor: "purple"
    },
    {
      label: "当前活跃度",
      value: "76",
      description: "+8.2%",
      icon: "DataAnalysis",
      iconColor: "orange",
      showPercentage: true
    }
  ])

  // 渠道绩效表格数据
  const channelTableData = ref<ChannelPerformance[]>([
    {
      channel: "华东区域服务商",
      totalProducts: 150,
      completedCount: 98,
      completionRate: 65.3,
      userCount: 98,
      validAccountCount: 87,
      totalContent: 2156,
      activeUsers: 85
    },
    {
      channel: "华南区域服务商",
      totalProducts: 120,
      completedCount: 76,
      completionRate: 63.3,
      userCount: 76,
      validAccountCount: 68,
      totalContent: 1843,
      activeUsers: 71
    },
    {
      channel: "华北区域服务商",
      totalProducts: 200,
      completedCount: 145,
      completionRate: 72.5,
      userCount: 145,
      validAccountCount: 132,
      totalContent: 3421,
      activeUsers: 138
    }
  ])

  // 内容发布趋势图数据
  const chartData = ref<ChartData>({
    contentTrend: {
      dates: ["08-01", "08-02", "08-03", "08-04", "08-05", "08-06"],
      published: [118, 135, 148, 162, 185, 208],
      generated: [145, 158, 178, 195, 218, 238]
    },
    versionActivity: {
      versions: ["标准版", "Pro版", "Pro Max"],
      values: [8.5, 15.2, 23.8]
    }
  })

  // 代理商排行数据
  const topAgentsData = ref<TopAgent[]>([
    {
      rank: 1,
      name: "上海代理商A",
      userCount: 45,
      contentCount: 1156,
      badge: "golden"
    },
    {
      rank: 2,
      name: "深圳代理商C",
      userCount: 38,
      contentCount: 967,
      badge: "silver"
    },
    {
      rank: 3,
      name: "北京代理商D",
      userCount: 35,
      contentCount: 934,
      badge: "bronze"
    },
    {
      rank: 4,
      name: "杭州代理商B",
      userCount: 32,
      contentCount: 823
    },
    {
      rank: 5,
      name: "广州代理商E",
      userCount: 28,
      contentCount: 756
    }
  ])

  // 用户版本分布数据
  const userVersionDistribution = ref<UserVersionDistribution[]>([
    {
      name: "标准版",
      value: 89,
      color: "#8b5cf6"
    },
    {
      name: "Pro版",
      value: 67,
      color: "#10b981"
    },
    {
      name: "Pro Max",
      value: 23,
      color: "#f59e0b"
    }
  ])

  // 处理时间范围变化
  const handleTimeRangeChange = async (value: string) => {
    timeRange.value = value
    console.log("时间范围变化:", value)
    await refreshData()
    // TODO: 根据时间范围重新获取数据
    // await fetchDataByTimeRange(value)
  }

  // 处理渠道筛选变化
  const handleChannelChange = async (value: string) => {
    channelFilter.value = value
    console.log("渠道筛选变化:", value)
    await refreshData()
    // TODO: 根据渠道筛选重新获取数据
    // await fetchDataByChannel(value)
  }

  // 刷新数据
  const refreshData = async () => {
    try {
      loading.value = true

      // TODO: 调用API获取数据
      // const [statsData, channelData, chartData, agentsData, distributionData] = await Promise.all([
      //   getStatsData(timeRange.value, channelFilter.value),
      //   getChannelPerformanceData(timeRange.value, channelFilter.value),
      //   getChartData(timeRange.value, channelFilter.value),
      //   getTopAgentsData(timeRange.value, channelFilter.value),
      //   getUserVersionDistribution(timeRange.value, channelFilter.value)
      // ])

      // 模拟API延迟
      await new Promise(resolve => setTimeout(resolve, 800))

      // TODO: 更新数据
      // statsCards.value = transformStatsData(statsData)
      // channelTableData.value = channelData
      // chartData.value = chartData
      // topAgentsData.value = agentsData
      // userVersionDistribution.value = distributionData

      console.log("数据刷新完成")
    } catch (error) {
      console.error("数据加载失败:", error)
      // TODO: 错误处理
      // ElMessage.error("数据加载失败，请重试")
    } finally {
      loading.value = false
    }
  }

  // 初始化数据
  const initData = async () => {
    await refreshData()
  }

  // 组件挂载时初始化数据
  onMounted(() => {
    initData()
  })

  return {
    // 状态
    loading,
    timeRange,
    channelFilter,

    // 数据
    statsCards,
    chartData,
    channelTableData,
    topAgentsData,
    userVersionDistribution,

    // 选项
    timeRangeOptions,
    channelOptions,

    // 方法
    handleTimeRangeChange,
    handleChannelChange,
    refreshData
  }
}

// 工具函数 - 格式化完成率显示
export function formatCompletionRate(rate: number): string {
  return `${rate.toFixed(1)}%`
}

// 工具函数 - 获取完成率状态颜色
export function getCompletionRateColor(rate: number): string {
  if (rate >= 70) return "var(--el-color-success)" // 成功色
  if (rate >= 60) return "var(--el-color-warning)" // 警告色
  return "var(--el-color-danger)" // 危险色
}

// 工具函数 - 格式化数字显示
export function formatNumber(num: number): string {
  if (num >= 1000) {
    return `${(num / 1000).toFixed(1)}k`
  }
  return num.toString()
}
